#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<vector<int>> fourSum(vector<int> &nums, int target)
{
    sort(nums.begin(), nums.end());
    int n = nums.size();
    vector<vector<int>> vv;
    for (int i = 0; i < n - 3;)
    {
        for (int j = i + 1; j < n - 2;)
        {
            int left = j + 1, right = n - 1;
            int aim = target - nums[i] - nums[j];
            while (left < right)
            {
                if(nums[left] + nums[right] < aim)
                {
                    left++;
                }
                else if(nums[left] + nums[right] > aim)
                {
                    right--;
                }
                else 
                {
                    vv.push_back({nums[i], nums[j], nums[left], nums[right]});
                    left++, right--;
                    while(left < right && nums[left] == nums[left - 1])
                    {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right + 1])
                    {
                        right--;
                    }
                }
            }
            j++;
            while(j < n - 2 && nums[j] == nums[j - 1])
            {
                j++;
            }
        }
        i++;
        while(i < n - 3 && nums[i] == nums[i - 1])
        {
            i++;
        }
    }
    return vv;
}
